import request from '@/utils/request'

// 证书管理服务基础API路径
const baseUrl = '/qep/certificate'

// 模拟数据 - 证书列表
const mockCertificates = [
  {
    id: 1,
    certificateNo: 'CERT-2023-001',
    productName: '管道阀门A型',
    batchNo: 'BATCH-2023-001',
    type: 'quality_certificate',
    templateName: '质量证明书模板A',
    templateId: 1,
    issueDate: '2023-10-15',
    issuer: '张工',
    certificateStatus: '有效',
    validUntil: '2024-10-15',
    exportFormat: 'PDF',
    remark: '常规质量证明',
    productId: 1,
    batchId: 1
  },
  {
    id: 2,
    certificateNo: 'CERT-2023-002',
    productName: '管道接头B型',
    batchNo: 'BATCH-2023-002',
    type: 'conformity_certificate',
    templateName: '合格证模板B',
    templateId: 2,
    issueDate: '2023-11-05',
    issuer: '李工',
    certificateStatus: '有效',
    validUntil: '2024-11-05',
    exportFormat: 'DOCX',
    remark: '特殊规格产品',
    productId: 2,
    batchId: 2
  },
  {
    id: 3,
    certificateNo: 'CERT-2023-003',
    productName: '管道连接器C型',
    batchNo: 'BATCH-2023-003',
    type: 'inspection_report',
    templateName: '检验报告模板C',
    templateId: 3,
    issueDate: '2023-12-10',
    issuer: '王工',
    certificateStatus: '已作废',
    validUntil: '2024-12-10',
    exportFormat: 'PDF',
    remark: '产品规格不符',
    voidReason: '产品规格与订单不符，需重新生产',
    productId: 3,
    batchId: 3
  },
  {
    id: 4,
    certificateNo: 'CERT-2024-001',
    productName: '管道阀门A型',
    batchNo: 'BATCH-2024-001',
    type: 'quality_certificate',
    templateName: '质量证明书模板A',
    templateId: 1,
    issueDate: '2024-01-20',
    issuer: '张工',
    certificateStatus: '有效',
    validUntil: '2025-01-20',
    exportFormat: 'PDF',
    remark: '常规质量证明',
    productId: 1,
    batchId: 4
  },
  {
    id: 5,
    certificateNo: 'CERT-2024-002',
    productName: '管道接头B型',
    batchNo: 'BATCH-2024-002',
    type: 'conformity_certificate',
    templateName: '合格证模板B',
    templateId: 2,
    issueDate: '2024-02-15',
    issuer: '李工',
    certificateStatus: '有效',
    validUntil: '2025-02-15',
    exportFormat: 'DOCX',
    remark: '特殊规格产品',
    productId: 2,
    batchId: 5
  }
];

// 获取证书列表
export function listCertificates(query) {
  console.log('Mock API: listCertificates', query);
  
  // 使用模拟数据
  let filteredCertificates = [...mockCertificates];
  
  // 应用筛选条件
  if (query) {
    if (query.certificateNo) {
      filteredCertificates = filteredCertificates.filter(cert => 
        cert.certificateNo.toLowerCase().includes(query.certificateNo.toLowerCase()));
    }
    if (query.productName) {
      filteredCertificates = filteredCertificates.filter(cert => 
        cert.productName.toLowerCase().includes(query.productName.toLowerCase()));
    }
    if (query.batchNo) {
      filteredCertificates = filteredCertificates.filter(cert => 
        cert.batchNo.toLowerCase().includes(query.batchNo.toLowerCase()));
    }
    if (query.type) {
      filteredCertificates = filteredCertificates.filter(cert => 
        cert.type === query.type);
    }
    if (query.certificateStatus) {
      filteredCertificates = filteredCertificates.filter(cert => 
        cert.certificateStatus === query.certificateStatus);
    }
  }
  
  // 处理分页
  const pageSize = query.pageSize || 10;
  const pageNum = query.pageNum || 1;
  const startIndex = (pageNum - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const pagedCertificates = filteredCertificates.slice(startIndex, endIndex);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    total: filteredCertificates.length,
    rows: pagedCertificates
  });
}

// 获取证书详情
export function getCertificate(id) {
  console.log('Mock API: getCertificate', id);
  const certificate = mockCertificates.find(cert => cert.id === parseInt(id));
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: certificate
  });
}

// 新增证书
export function addCertificate(data) {
  console.log('Mock API: addCertificate', data);
  // 创建新证书
  const newId = Math.max(...mockCertificates.map(cert => cert.id)) + 1;
  const newCertificate = {
    ...data,
    id: newId,
    certificateNo: `CERT-2024-${String(newId).padStart(3, '0')}`,
    certificateStatus: '有效'
  };
  
  mockCertificates.push(newCertificate);
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: newCertificate
  });
}

// 修改证书
export function updateCertificate(data) {
  console.log('Mock API: updateCertificate', data);
  const index = mockCertificates.findIndex(cert => cert.id === data.id);
  if (index !== -1) {
    mockCertificates[index] = { ...mockCertificates[index], ...data };
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 删除证书
export function deleteCertificate(id) {
  console.log('Mock API: deleteCertificate', id);
  const index = mockCertificates.findIndex(cert => cert.id === parseInt(id));
  if (index !== -1) {
    mockCertificates.splice(index, 1);
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 下载证书
export function downloadCertificate(id) {
  console.log('Mock API: downloadCertificate', id);
  // 模拟下载，返回一个空的PDF blob
  const certificate = mockCertificates.find(cert => cert.id === parseInt(id));
  
  // 创建一个简单的PDF blob (实际应用中这里会返回真实的PDF数据)
  const pdfContent = `%PDF-1.5
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /Resources 4 0 R /MediaBox [0 0 612 792] /Contents 6 0 R >>
endobj
4 0 obj
<< /Font << /F1 5 0 R >> >>
endobj
5 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
6 0 obj
<< /Length 68 >>
stream
BT
/F1 24 Tf
100 700 Td
(Certificate: ${certificate?.certificateNo || 'Unknown'}) Tj
ET
endstream
endobj
xref
0 7
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000216 00000 n
0000000259 00000 n
0000000326 00000 n
trailer
<< /Size 7 /Root 1 0 R >>
startxref
444
%%EOF`;
  
  const blob = new Blob([pdfContent], { type: 'application/pdf' });
  return Promise.resolve(blob);
}

// 签发证书
export function issueCertificate(id, data) {
  console.log('Mock API: issueCertificate', id, data);
  const index = mockCertificates.findIndex(cert => cert.id === parseInt(id));
  if (index !== -1) {
    mockCertificates[index].certificateStatus = '已签发';
    if (data) {
      mockCertificates[index] = { ...mockCertificates[index], ...data };
    }
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 作废证书
export function voidCertificate(id, reason) {
  console.log('Mock API: voidCertificate', id, reason);
  const index = mockCertificates.findIndex(cert => cert.id === parseInt(id));
  if (index !== -1) {
    mockCertificates[index].certificateStatus = '已作废';
    mockCertificates[index].voidReason = reason.voidReason;
  }
  
  return Promise.resolve({
    code: 200,
    msg: 'success'
  });
}

// 生成证书
export function generateCertificate(data) {
  console.log('Mock API: generateCertificate', data);
  return addCertificate(data);
}

// 获取证书数据
export function getCertificateData(certificateId) {
  console.log('Mock API: getCertificateData', certificateId);
  const certificate = mockCertificates.find(cert => cert.id === parseInt(certificateId));
  
  return Promise.resolve({
    code: 200,
    msg: 'success',
    data: certificate
  });
}

// 保存证书数据
export function saveCertificateData(data) {
  console.log('Mock API: saveCertificateData', data);
  return updateCertificate(data);
} 